package kr.pe.johnkim.sendme.rest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import kr.pe.johnkim.sendme.provider.SendMeBlock;
import kr.pe.johnkim.sendme.provider.SendMeInstall;
import kr.pe.johnkim.sendme.provider.SendMeMember;
import kr.pe.johnkim.sendme.provider.SendMeUser;
import kr.pe.johnkim.sendme.util.SendMeCommon;
import kr.pe.johnkim.sendme.util.SendMeConstant;
import android.util.Log;

public class SendMeUserRest {

	public static String TAG = SendMeUserRest.class.getSimpleName();
	
	
	/**
	 * 음성 메시지를 받는 사용자 목록을 가져 온다.
	 * 
	 * @param sendMeUser
	 * @return
	 */
	public ArrayList<SendMeUser> selectUserList(SendMeUser sendMeUser) {
		Log.i(TAG, "selectUserList");
		String url = SendMeConstant.SERVER_URL
				+ SendMeConstant.MAPPING_CONTROLLER
				+ SendMeConstant.USER_CONTROLLER
				+ SendMeConstant.SELECT_USER_LIST;

		ArrayList<SendMeUser> result = null;

		try {
			JSONObject parameterJsonObject = new JSONObject();
			parameterJsonObject.put("activateYn", "Y");
			parameterJsonObject.put("sendMeVoiceIdSendMeVoice", sendMeUser.getSendMeVoiceIdSendMeVoice());
			parameterJsonObject.put("sendMeVoiceSender", sendMeUser.getSendMeVoiceSender());
			
			String resultStr = this.requestToServer(url, parameterJsonObject.toString());
			
			if(resultStr.length()>0){
				JSONArray resultJsonArray = new JSONArray(resultStr);

				Log.d(TAG,"resultJsonArray:"+resultJsonArray.length());

				result = new ArrayList<SendMeUser>();
				/*
				 * [{
				 * "receiver":"01022173645",
				 * "activateYn":"Y",
				 * "modifyDate":"2014-02-19 11:51:27",
				 * "registerDate":"2014-02-19 11:51:27",
				 * "sendMeVoiceIdSendMeVoice":"146",
				 * "sendMeVoiceSender":"01088418653",
				 * "totalCount":null,"result":null,"receiverList":null},
				 * 
				 * {"receiver":"01011113333","activateYn":"Y",
				 * "modifyDate":"2014-02-19 11:51:27","registerDate":"2014-02-19 11:51:27",
				 * "sendMeVoiceIdSendMeVoice":"146","sendMeVoiceSender":"01088418653",
				 * "totalCount":null,"result":null,"receiverList":null
				 * }]
				 */
				
				for(int i=0; i<resultJsonArray.length(); i++){				
					JSONObject resultJsonObject = resultJsonArray.getJSONObject(i);

					SendMeUser tempSendMeUser = new SendMeUser();
					/*
					 * "receiver":"01022173645",						// * 받는사람 전번
					 * "activateYn":"Y",
					 * "registerDate":"2014-02-19 11:51:27",			// * 등록시간
					 * "sendMeVoiceIdSendMeVoice":"146",				// * 키
					 */
					tempSendMeUser.setReceiver(resultJsonObject.getString("receiver"));					// 그룹원의 전번
					tempSendMeUser.setActivateYn(resultJsonObject.getString("activateYn"));					// 유효성
					tempSendMeUser.setRegisterDate(resultJsonObject.getString("registerDate"));			// 등록시간
					tempSendMeUser.setSendMeVoiceIdSendMeVoice(resultJsonObject.getString("sendMeVoiceIdSendMeVoice"));				// 키

					// Y 인 것만 저장
					if(resultJsonObject.getString("activateYn").equals("Y")){
						result.add(tempSendMeUser);						
					}
				}
				
			}
			
		} catch(Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	
	
	/**
	 * 예약 음성 메시지의 수신자 목록을 업데이트 한다.
	 *   1. 기존의 수신자 목록을 비활성화 한다.
	 *   2. 새로 받은 수신자 목록을 등록 한다.
	 * @param sendMeUser
	 * @return
	 */
	public SendMeUser updateReservationUserList(SendMeUser sendMeUser){
		Log.i(TAG, "updateReservationUserList");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.USER_CONTROLLER
			+ SendMeConstant.UPDATE_RESERVATION_USER_LIST;
		
		SendMeUser result = new SendMeUser();
				
		try {
			JSONObject parameterJsonObject = new JSONObject();
			parameterJsonObject.put("activateYn", sendMeUser.getActivateYn());
			parameterJsonObject.put("sendMeVoiceIdSendMeVoice", sendMeUser.getSendMeVoiceIdSendMeVoice());
			parameterJsonObject.put("sendMeVoiceSender", sendMeUser.getSendMeVoiceSender());
			parameterJsonObject.put("receiverList", sendMeUser.getReceiverList());
			
			String resultStr = this.requestToServer(url, parameterJsonObject.toString());
			Log.d(TAG,"resultStr:"+resultStr);
			JSONObject resultJsonObject = new JSONObject(resultStr);
			result.setResult(resultJsonObject.getString("result"));
		} catch(Exception e) {
			e.printStackTrace();
		}	
		
		
//		/*
//		 * 이런식으로 사용
//		 */
//		try {
//			
//			JSONArray parameterJsonArray = new JSONArray();
//			
//			for(int i=0; i<sendMeUserList.size(); i++){
//				
//				SendMeUser sendMeUser = sendMeUserList.get(i);
//				
//				JSONObject parameterJsonObject = new JSONObject();
//				
//				parameterJsonObject.put("activateYn", sendMeUser.getActivateYn());
//				parameterJsonObject.put("modifyDate", sendMeUser.getModifyDate());
//				parameterJsonObject.put("registerDate", sendMeUser.getRegisterDate());
//				
//				parameterJsonObject.put("sendMeVoiceIdSendMeVoice", sendMeUser.getSendMeVoiceIdSendMeVoice());
//				parameterJsonObject.put("sendMeVoiceSender", sendMeUser.getSendMeVoiceSender());
//				parameterJsonObject.put("receiverList", sendMeUser.getReceiver());
//							
//				parameterJsonArray.put(parameterJsonObject.toString());		 // jsonArray 에 jsonObject 를 담아서 서버로 리스트를 보낼때는 jsonObject 그대로 넣지 않고 toString() 으로 변환하여 담는다				
//			}
//			String resultStr = this.requestToServer(url, parameterJsonArray.toString());
//			Log.d(TAG,"resultStr :"+resultStr);
//		} catch(Exception e) {
//			e.printStackTrace();
//		}
		
		
		
		return result;
	}
	
	
	
	
	
	



	
	
	
	
	
	
	
	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	
	/**
	 * http protocal 을 사용하는 서버 요청 공통 메소드.
	 * 요청 후 결과를 json string 으로 받아서 반환 한다.
	 * 
	 * @param url
	 * @param inputJsonString
	 * @return
	 */
	public String requestToServer(String url, String inputJsonString) {
		Log.i(TAG, "requestToServer");
		
		String result = "";
		
		try {
			URL postUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(inputJsonString.getBytes());
	        os.flush();
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        		result = bufferedReader.readLine();
	        	}
	        }
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
}
